
using Backoffice.Domain.Repositories;
using Backoffice.Domain.Entities;
using Backoffice.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Backoffice.Application.Common;
using BackOffice.Application.DTOs;

namespace Backoffice.Infrastructure.Repositories;




public class EfRepository<T> : IRepository<T> where T : EntityBase
{


    protected readonly BackOfficeDbContext _dbContext;

    public EfRepository(BackOfficeDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public virtual async Task<IEnumerable<T>> GetAllAsync()
    {
        return await _dbContext.Set<T>()
            .ToListAsync();
    }

    public virtual async Task<T?> GetByIdAsync(Guid id)
    {
        return await _dbContext.Set<T>()
            .FirstOrDefaultAsync(e => e.Id == id);
    }

    public virtual async Task<T> CreateAsync(T entity)
    {
        _dbContext.Set<T>().Add(entity);
        await _dbContext.SaveChangesAsync();
        return entity;
    }

    public virtual async Task UpdateAsync(T entity)
    {
        entity.UpdatedAt = DateTime.UtcNow; // 更新时间戳

        var entry = _dbContext.Entry(entity);
        entry.State = EntityState.Modified;

        await _dbContext.SaveChangesAsync();
    }

    public virtual async Task DeleteAsync()
    {
        // 无参数版本的删除方法 - 这里可以根据具体需求实现
        // 例如：删除所有实体，或者抛出异常表示需要指定ID
        throw new NotImplementedException("DeleteAsync() without id is not supported. Please use DeleteAsync(Guid id) instead.");
    }

    public virtual async Task DeleteAsync(Guid id)
    {
        var entity = await _dbContext.Set<T>().FindAsync(id);

        if (entity != null)
        {
            // 硬删除实现 - 直接从数据库中物理删除
            _dbContext.Set<T>().Remove(entity);
            await _dbContext.SaveChangesAsync();
        }
    }



    public IQueryable<T> Query()
    {
        // 返回所有实体的 IQueryable
        return _dbContext.Set<T>();
    }
}


